package com.tjbank.cssys.service.impl;

import java.util.*;

import com.tjbank.cssys.framework.base.enums.YesOrNoEnum;
import com.tjbank.cssys.framework.base.exception.ServiceException;
import com.tjbank.cssys.framework.base.util.GeneratIDUtil;
import com.tjbank.cssys.mybatis.mapper.IamRelationshipMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tjbank.cssys.api.PermissionService;
import com.tjbank.cssys.dto.PermissionDTO;
import com.tjbank.cssys.mybatis.IamApiDao;
import com.tjbank.cssys.mybatis.IamMenuDao;
import com.tjbank.cssys.mybatis.IamPermissionDao;
import com.tjbank.cssys.mybatis.IamRelationshipDao;
import com.tjbank.cssys.mybatis.entity.IamApi;
import com.tjbank.cssys.mybatis.entity.IamApiKey;
import com.tjbank.cssys.mybatis.entity.IamMenu;
import com.tjbank.cssys.mybatis.entity.IamMenuKey;
import com.tjbank.cssys.mybatis.entity.IamPermission;
import com.tjbank.cssys.mybatis.entity.IamPermissionKey;
import com.tjbank.cssys.mybatis.sqlbuilder.IamPermissionSqlBuilder;
import com.tjbank.cssys.mybatis.sqlbuilder.IamRelationshipSqlBuilder;
import com.tjbank.cssys.service.convert.PermissionConvert;
import com.tjbank.cssys.service.enums.PermTypeEnum;
import com.tjbank.cssys.service.util.PermissionUtil;

/**
 * 权限
 * 
 * Package : com.tansun.magicube.iam.service.impl
 * 
 * @author -- lijiangtao 2020年5月9日 下午6:57:04
 *
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private IamPermissionDao permissionDao;

    @Autowired
    private IamRelationshipDao relationshipDao;

    @Autowired
    private IamApiDao apiDao;

    @Autowired
    private IamMenuDao menuDao;
    @Autowired
    private IamRelationshipMapper iamRelationshipMapper;

    @Value("${orginGrade}")
    //一级机构
    private String orginGrade;
    @Value("${secondOrginGradeNoMenueUrl}")
    //二级机构不展示的菜单
    private String secondOrginGradeNoMenueUrl;


    /**
     * 新增
     * 
     * @param permissionDTO
     * @return
     * @author -- lijiangtao 2020年5月9日 下午6:57:17
     */
    @Override
    @Transactional
    public Integer addPermission(PermissionDTO permissionDTO) {
//        this.checkParam(permissionDTO);
        IamPermission entity = PermissionConvert.INSTANCE.dtoToEntity(permissionDTO);
        entity.setId(GeneratIDUtil.getUUId());
        entity.setPermType(PermTypeEnum.MENU_PERM.getCode());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        return permissionDao.insert(entity);
    }

//    /**
//     * 校验权限编码
//     * 
//     * @param permissionDTO 
//     * @author -- lijiangtao 2020年8月18日 下午12:45:23
//     */
//    private void checkParam(PermissionDTO permDTO) {
//        IamPermissionSqlBuilder sqlBuilder = new IamPermissionSqlBuilder();
//        sqlBuilder.andMenuIdEqualTo(permDTO.getMenuId()).andPermNumEqualTo(permDTO.getPermNum());
//        if (!Objects.isNull(permissionDao.selectBySqlBuilder(sqlBuilder))) {
//            throw new ServiceException("权限编码已存在");
//        }
//    }
    
    
    /**
     * 菜单权限
     * 
     * 接口权限
     * 
     * @param permissionDTO
     * @return
     * @author -- lijiangtao 2020年7月24日 上午10:18:27
     */
    @Override
    public List<PermissionDTO> permissionTreeList(PermissionDTO permissionDTO) {
        if (StringUtils.isEmpty(permissionDTO.getPermType())) {
            throw new ServiceException("权限类型不能为空");
        }
        //判断是否是二级机构
        Map<String,String>mapResult= iamRelationshipMapper.selectOrginIdByuserCode(permissionDTO.getLoginCode());

//		Permission permission = PermissionConvert.INSTANCE.dtoToPermission(permissionDTO);
//		List<PermissionDTO> permissionList = PermissionConvert.INSTANCE.permsToDtoList(permissionMapper.queryPerissionToTree(permission));

        IamPermissionSqlBuilder sqlBuilder = new IamPermissionSqlBuilder();
        sqlBuilder
                .andPermTypeEqualTo(
                        (Objects.deepEquals(permissionDTO.getPermType(), PermTypeEnum.MENU_PERM.getCode())) ? PermTypeEnum.MENU_PERM.getCode() : PermTypeEnum.API_PERM.getCode())
                .andIsDeletedEqualTo(YesOrNoEnum.NO.getCode());
        if (StringUtils.isNotBlank(permissionDTO.getPermName())) {
            sqlBuilder.andPermNameLikeBoth(permissionDTO.getPermName());
        }
        List<PermissionDTO> permissionList = PermissionConvert.INSTANCE.entitiesToDtoList(permissionDao.selectListBySqlBuilder(sqlBuilder));
        for (PermissionDTO permission : permissionList) {
            IamMenu menu = menuDao.selectByPrimaryKey(new IamMenuKey(permission.getId()));
            IamApi api = apiDao.selectByPrimaryKey(new IamApiKey(permission.getApiId()));
            permission.setMenuUrl(Objects.isNull(menu) ? null : menu.getMenuUrl());
            permission.setMenuSort(Objects.isNull(menu) ? null:menu.getMenuSort());
            permission.setApiUrl(Objects.isNull(api) ? null : api.getApiUrl());
        }
        if (null != mapResult && !orginGrade.equals(mapResult.get("type"))) {
            String[] menueUrl = secondOrginGradeNoMenueUrl.split(",");
            List<String> menuList = new LinkedList<>(Arrays.asList(menueUrl));
            Iterator iterator = permissionList.iterator();
            while (iterator.hasNext()) {
                PermissionDTO permissi = (PermissionDTO) iterator.next();
                for (String menueUrlList : menuList) {
                    if (menueUrlList.equals(permissi.getMenuUrl())) {
                        iterator.remove();
                    }
                }
            }
        }
        return PermissionUtil.listToTree(permissionList);
    }

    /**
     * 编辑
     * 
     * @param permissionDTO
     * @return
     * @author -- lijiangtao 2020年6月21日 下午7:41:49
     */
    @Override
    public Integer updatePermission(PermissionDTO permissionDTO) {
        this.checkPermissionId(permissionDTO.getId());
        IamPermission entity = PermissionConvert.INSTANCE.dtoToEntity(permissionDTO);
        entity.setUpdateTime(new Date());
        IamPermissionSqlBuilder sqlBuilder = new IamPermissionSqlBuilder();
        sqlBuilder.andIdEqualTo(entity.getId());
        return permissionDao.updateBySqlBuilder(entity, sqlBuilder);
    }

    /**
     * 删除权限
     * 
     * @param permissionId
     * @return
     * @author -- lijiangtao 2020年6月21日 下午7:41:56
     */
    @Override
    public Integer deletePermission(String permissionId) {
        this.checkPermissionId(permissionId);
        IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
        sqlBuilder.andEntity2CodeEqualTo(permissionId);
        relationshipDao.deleteBySqlBuilder(sqlBuilder);
        return permissionDao.deleteByPrimaryKey(new IamPermissionKey(permissionId));
    }

    /**
     * 校验权限ID
     * 
     * @param permissionId
     * @author -- lijiangtao 2020年6月21日 下午7:42:48
     */
    private void checkPermissionId(String permissionId) {
        if (StringUtils.isBlank(permissionId)) {
            throw new ServiceException("权限ID不能为空");
        }
    }
}
